<template>
    <div>
      <el-popover
          placement="bottom"
          :width="selectTableWidth"
          trigger="manual"
          v-model="showTree"
      >
        <div class="treeDiv" ref="tableList">
          <div class="flex justify_between mb10">
            <div style="display: flex">
              <el-input v-model="getTabQuery" class="search" type="text" placeholder="模糊搜索" size="small"></el-input>
              <el-button style="margin-left: 5px;" type="primary" size="small" @click="getTableData" plain>查询</el-button>
            </div>
            <div>
              <el-button type="primary" size="small" @click="addTab">添加</el-button>
              <el-button type="danger" size="small" plain @click="batchDelTab">删除</el-button>
            </div>
          </div>
          <el-table
              ref="tab"
              :data="tableData"
              :row-class-name="tableRowClassName"
              @cell-dblclick="dbClickEditData"
              :header-cell-style="getRowClass"
              @selection-change="selectionChangeHandle"
              style="width: 100%"
          >
            <el-table-column align="center" type="selection" width="55"></el-table-column>
            <template v-for="(item, index) in tableColumn">
              <el-table-column
                  :key="index"
                  :prop="item.prop"
                  :label="item.label"
                  :width="item.width"
                  align="left"
              >
                <template #default="scope">
                  <div v-if="tbRow == scope.row && tbCol == scope.column.id">
                    <component v-if="!item.custom && item.type == 'select'" :is="'el-'+item.type" size="mini" filterable clearable v-model="scope.row[item.prop]" :ref="'tabInput' + tbCol" @blur="onBlur(scope.row, scope.column)">
                      <el-option :key="'dic_'+index" :label="dic.label" :value="dic.value" v-for="(dic,index) in item.dicData"></el-option>
                    </component>
                    <component v-else-if="!item.custom && item.type == 'cascader'" :is="'el-'+item.type" size="mini" filterable clearable @blur="onBlur(scope.row, scope.column)" :append-to-body="true"
                               v-model="scope.row[item.prop]" :ref="'tabInput' + tbCol" :options="item.options()" :props="item.props"></component>
                    <commonSelect v-else-if="item.custom && item.type == 'Treeselect'" v-model="scope.row[item.prop]" node-key="value" :multiple="false" :options="item.options()"></commonSelect>
                    <color-selector v-else-if="item.custom && item.type == 'my-color-picker'" v-model="scope.row[item.prop]"></color-selector>
                    <component v-else :is="'el-'+item.type" size="mini" v-model="scope.row[item.prop]" :ref="'tabInput' + tbCol" @blur="onBlur(scope.row, scope.column)"></component>
                  </div>
                  <span v-else>{{ scope.row[item.prop] }}</span>
                </template>
              </el-table-column>
            </template>
            <el-table-column v-if="isShowBtns" align="center" label="操作">
              <template #default="scope">
                <i
                    class="el-icon-remove-outline"
                    style="color: red; font-size: 21px;cursor: pointer;"
                    @click.stop="delTab(scope.row, scope.$index)"
                ></i>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              @size-change="dolNandleSizeChange"
              @current-change="dolHandleCurrentChange"
              :current-page="pageData.pageNum"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageData.total"
          >
          </el-pagination>
        </div>
        <div class="select-table-query" slot="reference">
            <el-input
                size="small"
                @change="changeTab"
                v-model="selectDataValue"
                :placeholder="inputPlaceholder"
                :suffix-icon="showTree ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                @click.native="deptogglePanel($event)"
            ></el-input>
        </div>
      </el-popover>
    </div>
</template>
<script>
import commonSelect from "./commonSelectTree"
import ColorSelector from "./colorSelector";
import baseComp from "./baseComp";

export default {
    name: "selectTable",
  components: {ColorSelector, commonSelect},
    extends: baseComp,
    model: {
        prop: "value",
        event: "selectChange",
    },
    props: {
        tableColumn: {
            type: Array,
            default: () => [],
        },
        value: {
            type: Array,
            default: () => [],
        },
        selectKey: {
            type: String,
            default: () => "",
        },
        //地址
        getTabUrl: {
            type: String,
            default: () => "",
        },
        //方法
        getTabMethod: {
            type: String,
            default: () => "",
        },
        inputPlaceholder: {
            type: String,
            default: "",
        },
        // 是否显示操作列表按钮
        isShowBtns: {
            type: Boolean,
            required: false,
            default: true,
        },
        selectTableWidth: {
            type: Number,
            default: 600
        }
    },
    data() {
        return {
            tbRow: "",
            tbCol: "",
            pageData: {
                total: 0,
                pageSize: 10,
                pageNum: 1,
            },
            tableData: [],
            localTableData: this.value,
            selectDataValue: "",
            multipleSelection: [],
            getTabQuery: "",
            showTree: false,
        };
    },
    watch: {
        // value: {
        //     handler(val) {
        //         this.localTableData = val;
        //         this.getTableData();
        //     },
        //     immediate: true,
        //     deep: true,
        // }
    },
    mounted() {
        this.getTableData()
    },
    methods: {
        /**
         * 行样式，给每行添加一个index索引，用于对数据进行新增删除操作
         */
        tableRowClassName({row, rowIndex}){
          row.index = rowIndex;
        },
        // 获取查询数据
        getTableData() {
            if (this.getTabMethod != "" && this.getTabUrl != "") {
                let queryData = {...this.getTabQuery, ...this.pageData};
                this.$myAxios.request(
                    this.getTabMethod,
                    this.getTabUrl,
                    queryData
                ).then((res) => {
                    if (res.data.code == 200) {
                        this.tableData = res.data.data;
                        this.pageData.total = res.data.total;
                    }
                });
            }else {
              let filterData = this.localTableData.filter(item => {
                let content = "";
                for (let itemKey in item) {
                  content += item[itemKey];
                }
                if (content.indexOf(this.getTabQuery) >= 0){
                  return true;
                }
                return false;
              })
              //过滤数据静态分页
              this.dataPagination(filterData);
            }
        },
        /**
         * 表格静态分页
         */
        dataPagination(dataList) {
          if (!dataList || dataList.length <=0) {
            dataList = [];
            this.tableData = [];
          }
          this.pageData.total = dataList.length;
          if (dataList.length <= this.pageData.pageSize) {
            this.tableData = dataList;
            return;
          }
          let pageNo = this.pageData.pageNum;
          let pageSize = this.pageData.pageSize;
          const offset = (pageNo - 1) * pageSize;
          this.tableData = (offset + pageSize >= dataList.length) ? dataList.slice(offset, dataList.length) : dataList.slice(offset, offset + pageSize);
        },
        // 点击input 阻止冒泡 控制table显示隐藏
        deptogglePanel(event) {
            event || (event = window.event);
            event.stopPropagation
                ? event.stopPropagation()
                : (event.cancelBubble = true);
            this.showTree ? this.tableHide() : this.tableShow();
        },
        /**
         * 显示表格
         */
        tableShow() {
            this.showTree = true;
            document.addEventListener("click", this.tableHideList, false);
        },
        /**
         * 隐藏表格
         */
        tableHide() {
            this.showTree = false;
            document.addEventListener("click", this.tableHideList, false);
        },
        /**
         * 表格隐藏显示事件
         */
        tableHideList(e) {
            if (
                this.$refs.tableList &&
                !this.$refs.tableList.contains(e.target)
            ) {
                this.tableHide();
            }
        },
        /**
         * 分页事件，每页改变数量级
         */
        dolNandleSizeChange(val) {
            this.pageData.pageSize = val;
            this.pageData.pageNum = 1;
            this.getTableData();
        },
        /**
         * 分页事件，改变页数
         */
        dolHandleCurrentChange(val) {
            this.pageData.pageNum = val;
            this.getTableData();
        },
        //把表格头变成灰色
        getRowClass({ rowIndex }) {
            if (rowIndex === 0) {
                return "background: #FAFAFA;border-bottom:#E8E8E8!impotant;color: #333333;";
            } else {
                return "";
            }
        },
        // 手动输入
        changeTab() {},
        /**
         * 表格选中事件
         */
        selectionChangeHandle(val) {
            this.multipleSelection = val;
            this.selectDataValue = val
                .map((item) => {
                    return item[this.selectKey];
                })
                .join(",");
            this.$emit("selectChange", this.multipleSelection);
        },
        //表格行双击事件
        dbClickEditData(r, c) {
            this.tbRow = r;
            this.tbCol = c.id;
            // this.$nextTick(() => {
            //   let focus = this.$refs["tabInput" + c.id][0].focus;
            //   if (typeof focus == 'function'){
            //     focus();
            //   }
            // });
        },
        /**
         * 元素失去焦点事件
         */
        onBlur(r, c){
          this.tbRow = "";
          this.tbCol = "";
        },
        /**
         * 添加数据行
         */
        addTab() {
            let column = {};
            this.tableColumn.forEach(item => {
                column[item.prop] = '';
            })
            column['id'] = Math.random();
            this.localTableData.push(column);
            // this.tbRow = column
            // this.tbCol =
            this.getTableData();
        },
        /**
         * 单行删除事件
         */
        delTab(row, index) {
            // //上传到父级事件
            // this.$emit("multipleSelection",this.multipleSelection)
            this.tableData.splice(index, 1);
            let localIndex = this.localTableData.findIndex(item => item.id == row.id);
            this.localTableData.splice(localIndex, 1);
            this.getTableData();
        },
        /**
         * 批量删除指定数据
         */
        batchDelTab(){
            this.multipleSelection.forEach(item => {
                this.tableData.splice(item.index, 1);
                let localIndex = this.localTableData.findIndex(item_ => item_.id == row.id);
                this.localTableData.splice(localIndex, 1);
            })
            this.getTableData();
        },
      // 字段默认 id label 用于规范化数据源
      tenantIdnormalizer(node, instanceId) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.value,
          label: node.label,
          children: node.children
        }
      }
    },
};
</script>
<style scoped lang="less">
::v-deep {
    .select-table-query {
        position: relative;
        .el-input {
            width: 300px;
        }
    }
    .treeDiv {
        width: 500px;
        margin-top: 10px;
        background-color: #ffffff;
        border: 1px solid #e5e5e5;
        border-radius: 4px;
        padding: 10px;
        .search {
            width: 200px;
            margin-right: 10px;
        }
        .el-table {
            border: 1px solid #ccc;
            border-radius: 6px;
        }
        .el-table td {
            padding: 4px 0;
        }
        .el-table td:first-child {
            border-left: none;
            border-right: none;
        }
    }
    .el-pagination {
        text-align: right;
        margin-top: 12px;
    }

  .vue-treeselect__menu-container{
    position: absolute;
    .vue-treeselect__meun{
      z-index: 90000000;
      position: relative;

    }
  }

}
</style>
